package cn.shadow.game.chess.CHnchess;

import cn.shadow.game.chess.AbstractChessGame;
import cn.shadow.game.chess.CHnchess.board.Board;
import cn.shadow.game.chess.CHnchess.board.CHnChessBoard;
import cn.shadow.game.chess.CHnchess.board.Mover;
import cn.shadow.game.chess.CHnchess.chessman.Chess;
import cn.shadow.game.chess.CHnchess.mesage.CHChessModuleMessages;
import cn.shadow.proto.client.CHnChessClientProtoContent.*;
import com.google.protobuf.MessageOrBuilder;
import io.netty.buffer.ByteBuf;

public class ChnChessGame extends AbstractChessGame {

    public ChnChessGame() {
        this.iboard = new CHnChessBoard();
    }

    @Override
    public void reset() {
        iboard.reset();
        sendInitMsg();
    }

    @Override
    public void init() {
        reset();
    }

    @Override
    public void putChessPosition(int i, int j) {
        if (i >= Board.ROW || j >= Board.COL || i < 0 || j < 0) {
            return;
        }
        boolean before = iboard.isBlack();
        iboard.click(i, j);
        sendChosenMsg();
        boolean after = iboard.isBlack();
        if (before != after) { //如果下棋方发生改变
            sendStepMsg();  //发送一次移动的消息
            sendTipsWho(); //提示到哪一方了
            sendCheckMateMsg(); //发送将军消息
        }
        if (iboard.isOver()) {
            doWhenFinish();
        }
    }

    /**
     * 发送将军的数据
     */
    private void sendCheckMateMsg() {
        CHnChessBoard board = (CHnChessBoard) iboard;
        CheckmateTip checkmateTip = board.checkmateTipMsg();
        if (checkmateTip == null) {
            return;
        }
        sendToAll(CHChessModuleMessages.CheckmateTipMsg(checkmateTip.toByteArray()));
    }

    private void sendTipsWho() {

    }

    private void sendChosenMsg() {
        CHnChessBoard board = (CHnChessBoard) iboard;
        Chess chose = board.getChose();
        if (chose != null) {
            ChessNode chessNode = (ChessNode) chose.getPosition().chessNodeMsg();
            sendToAll(CHChessModuleMessages.ChosenMsg(chessNode.toByteArray()));
        }
    }

    @Override
    public void sendInitMsg() {
        CHnChessBoard chessBoard = (CHnChessBoard) iboard;
        CurrentBoard currentBoard = chessBoard.currentBoard();
        sendToAll(CHChessModuleMessages.InitChessMsg(currentBoard.toByteArray()));
    }

    @Override
    public void sendStepMsg() {
        CHnChessBoard chessBoard = (CHnChessBoard) iboard;
        Mover mover = chessBoard.getMovers().peek();
        ChessMoverMsg moverMsg = (ChessMoverMsg) mover.moverMsg();
        sendToAll(CHChessModuleMessages.MoveMsg(moverMsg.toByteArray()));
    }

    @Override
    public void doWhenFinish() {
        sendResult();
        iboard.setOver(true);
    }

    private void sendResult() {

    }

    protected void sendToAll(ByteBuf message) {
        sendPlayerMsg(message);
        notifyAllViewer(message);
    }
}
